#include "snakeGame.h"
#include <conio.h>
#include "utility.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE); 




snakeGame::snakeGame()
{


	system( "color 0B" );
	

	SetConsoleTextAttribute(color, 12);
	for(int i=20; i< 30;i++ )
	{
		setCursor(i,14);
		cout << "*";
	}
	
	for(int i=20; i< 30;i++ )
	{
		setCursor(i,8);
		cout << "*";
	}
	for(int i=8; i< 15;i++ )
	{
		setCursor(10,i);
		cout << "*";
	}
	head=new node(1,14,15);

	tail=new node('*',12,head->y);

	tail->next=NULL;

	head->prev=NULL;

	head->next=tail;

	tail->prev=head;

	addToTail(13,head->y);

	

	createFruit();

	createFruit();

	createFruit();
	
}
void snakeGame::print()
{
	SetConsoleTextAttribute(color, 15);
	node*t=head;
	while(t!=NULL)
	{
		setCursor(t->x,t->y);
		cout << t->ch;
		t=t->next;
	}
	
}
void snakeGame::addToTail(int x,int y )
{
	node*p=new node('*',x,y);
	p->next=tail;
	p->prev=tail->prev;
	tail->prev->next=p;
	tail->prev=p;
}
void snakeGame::createFruit()
{
	SetConsoleTextAttribute(color, 13);
	setCursor(35,20);
	int x,y;
	srand(time(0));
	
	while(1)
	{
		x=rand()% 42;
        y=rand()% 22;
		if(readFrom(x,y)!='*' && readFrom(x,y)!= head->ch  && readFrom(x,y)!= '@')
		{
			setCursor(x,y);
			cout<<'@';
			break;
		}
	}
}
void snakeGame::move()
{
	char c;
	char direction='r';
	while(1)
	{
		nextMove();

		if(kbhit())
		{
			c = getch(); // to ignore key press
			c = getch(); // to catch key release
			if(c == 72)//up key
			{ 
				if(direction!='d')
				{
					direction='u';
				}
			}
			else if(c == 80)//down key
			{
				if(direction!='u')
				{
					direction='d';
				}
			
			}
			else if(c == 75)//left key
			{ 
				if(direction!='r')
				{
					direction='l';
				}
			}
			else if(c == 77)//right key
			{ 

				if(direction!='l')
				{
					direction='r';
				}
			}
		}
		else if(direction=='r')
		{	
			head->x++;
			if(head->x > 49)
			{
				head->x=0;
			}
		}
		else if(direction=='l')
		{
			head->x--;
			if(head->x < 0)
			{
				head->x=49;
			}
		}
		else if(direction=='u')
		{
			head->y--;
			if(head->y < 0)
			{
				head->y=24;
			}
		}
		else if(direction=='d')
		{
			head->y++;
			if(head->y > 25)
			{
				head->y=0;
			}
		}
		onCollision();
		print();
        Sleep(100);
        setCursor(tail->x,tail->y);
        cout<<" ";
	}
}
void snakeGame::startGame()
{
	move();
}
void snakeGame::onCollision()
{
	if(readFrom(head->x,head->y)=='*')
	{
		system("cls");
		setCursor(24,12);
		cout << "Game Over...\n";
		
		cout << endl << endl;
		exit(0);
	}
	else if(readFrom(head->x,head->y)=='@')
	{
		addToTail(tail->x,tail->y);
		createFruit();
	}
}
void snakeGame::nextMove()
{
	node*p=tail;
	while(p!=head)
	{
		p->x=p->prev->x;
		p->y=p->prev->y;
		p=p->prev;
	}

}
snakeGame::~snakeGame(void)
{
	while(head!=NULL)
	{
		head=head->next;
		delete head->prev;
	}

}
